package com.zw.rpc.server.config;

import com.zw.rpc.Request;
import com.zw.rpc.ServiceDescriptor;
import com.zw.rpc.common.utils.ReflectionUtils;
import lombok.extern.slf4j.Slf4j;

import java.lang.reflect.Method;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * 管理rpc暴露的服务
 *
 * @author zw
 */
@Slf4j
public class ServiceManager {

    private Map<ServiceDescriptor, ServiceInstance> services;

    public ServiceManager() {
        this.services = new ConcurrentHashMap<>();
    }

    /**
     * 注册服务
     *
     * @param interfaceClass 接口
     * @param beam 接口实现
     * @param <T>
     */
    public <T> void register(Class<T> interfaceClass, T beam) {
        List<Method> publicMethod = ReflectionUtils.getPublicMethod(interfaceClass);
        publicMethod.forEach(method -> {
            ServiceInstance serviceInstance = new ServiceInstance(beam,method);
            ServiceDescriptor serviceDescriptor = ServiceDescriptor.from(interfaceClass,method);
            services.put(serviceDescriptor,serviceInstance);
            log.info("register service : {} {}",serviceDescriptor.getClazz(),serviceDescriptor.getMethod());
        });
    }

    public ServiceInstance lookup(Request request) {
        ServiceDescriptor serviceDescriptor = request.getServiceDescriptor();
        return services.get(serviceDescriptor);
    }

}
